package com.express.interceptor;

import com.express.service.TokenService;
import com.express.util.Verification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {

  private Logger logger = LoggerFactory.getLogger(getClass());

  @Autowired
  TokenService iTokenService;

  public LoginHandlerInterceptor(TokenService iTokenService) {
    this.iTokenService = iTokenService;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          throws Exception {
    String uriLong = request.getRequestURI();
    String uri = uriLong.substring(uriLong.indexOf("/", 2));
    String token = request.getHeader("token");
    String method = request.getMethod();
//    this.logger.info("uri=" + uri);
    if ("OPTIONS".equals(method)) {
      return true;
    }
    if (Verification.noToken(uri)) {
      return true;
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
          throws Exception {
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
          throws Exception {
  }
}